﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using FlowBasisSampleSite.Domain.Entities;
using System.Data.Entity.ModelConfiguration;

namespace FlowBasisSampleSite.Domain
{
    public class DomainContext : DbContext
    {
        public DomainContext() : base(System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString)
        {            
        }

        public DbSet<UserAccount> UserAccounts { get; set; }       
        public DbSet<Role> Roles { get; set; }
        public DbSet<Permission> Permissions { get; set; }

        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            ConfigureUserAccount(modelBuilder.Entity<UserAccount>());            
            ConfigureRole(modelBuilder.Entity<Role>());
            ConfigurePermission(modelBuilder.Entity<Permission>());            
        }

        private void ConfigureUserAccount(EntityTypeConfiguration<UserAccount> model)
        {
            model.HasKey(ua => ua.UserAccountId)
                .ToTable("UserAccount");
           
            model.HasMany<Role>(u => u.Roles)             
                .WithMany(r => r.UserAccounts)
                .Map(m =>
                {                 
                    m.ToTable("UserRoleMembership");
                    m.MapLeftKey("UserAccountId");
                    m.MapRightKey("RoleId");
                });
        }

        private void ConfigureRole(EntityTypeConfiguration<Role> model)
        {
            model.HasKey(r => r.RoleId)
                .ToTable("Role");
           
            // Role.UserAccounts configured from UserAccount side.
            // Role.Permissions configured from Permission side.
        }

        private void ConfigurePermission(EntityTypeConfiguration<Permission> model)
        {
            model.HasKey(p => p.PermissionId)
                .ToTable("Permission");

            model.HasMany<Role>(p => p.Roles)
                .WithMany(r => r.Permissions)
                .Map(m =>
                {
                    m.ToTable("RolePermissionAssignment");
                    m.MapLeftKey("PermissionId");
                    m.MapRightKey("RoleId");
                });
        }       
    }
}
